﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace MetaSharp.Transformation.Patterns
{
    class OneOrMorePattern : Pattern
    {
        public Pattern Pattern { get; private set; }
        public OneOrMorePattern(Pattern pattern)
            : base(PatternKind.OneOrMore)
        {
            this.Pattern = pattern;
        }

        public override PatternMatch Compile()
        {
            var p = Pattern.Compile();
            return s => Target(s, p);
        }

        private static async Task<IMatch> Target(IScope scope, PatternMatch pattern)
        {
            if (pattern.Method.Name == "Not")
                throw new NotSupportedException("Invalid combination of !x+ (not x, one or more).");

            var end = scope;
            var matches = new List<object>();
            while (true)
            {
                var r = await pattern(end);
                if (!r.Matched)
                    break;

                end = r.End;
                matches.Add(r.Value);
            }

            if (matches.Count > 0)
                return new Match(
                    matches.ToArray(),
                    scope,
                    end);

            return await Transformation.Match.Fail(scope);
        }
    }
}
